<template>
  <el-dialog
    v-model="dialogShow"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    custom-class="mydialog"
    width="800px"
    :title="titleContent"
    :before-close="close"
  >
    <el-form
      ref="formRef"
      :model="productInfo"
      :rules="rules"
      :label-width="formLabelWidth"
      size="small"
    >
      <el-row :gutter="40">
        <el-col
          v-if="dialogType!=='create'"
          :span="12"
        >
          <el-form-item
            label="产品编号"
            prop="productNumber"
          >
            <el-input
              v-model="productInfo.productNumber"
              :disabled="dialogType!=='create'"
              clearable
              placeholder="请输入产品编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="通用名"
            prop="productPopularName"
          >
            <el-input
              v-model="productInfo.productPopularName"
              clearable
              placeholder="请输入通用名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="产品别名"
            prop="productAlias"
          >
            <el-input
              v-model="productInfo.productAlias"
              clearable
              placeholder="请输入产品别名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="商品名"
            prop="productName"
          >
            <el-input
              v-model="productInfo.productName"
              clearable
              placeholder="请输入商品名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="批准文号"
            prop="approvalNumber"
          >
            <el-input
              v-model="productInfo.approvalNumber"
              clearable
              placeholder="请输入批准文号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="包装规格"
            prop="packSpecs"
          >
            <el-input
              v-model="productInfo.packSpecs"
              clearable
              placeholder="请输入包装规格，如：1.5*10g/盒"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="生产厂家"
            prop="producer"
          >
            <el-input
              v-model="productInfo.producer"
              clearable
              placeholder="请输入生产厂家"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="剂型"
            prop="drugForm"
          >
            <el-select
              ref="drug"
              v-model="productInfo.drugForm"
              style="width: 100%"
              clearable
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择剂型"
              @visible-change="drugChange"
            >
              <el-option
                v-for="(itm, idx) in drugOptions"
                :key="itm.id"
                :label="itm.label"
                :value="itm.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="计价单位"
            prop="sellUnit"
          >
            <el-select
              v-model="productInfo.sellUnit"
              style="width: 100%"
              clearable
              filterable
              allow-create
              :reserve-keyword="false"
              placeholder="请选择或输入计价单位"
              @visible-change="(val)=>{sellUnitChange(val,'sellUnit')}"
            >
              <el-option
                v-for="(itm, idx) in sellUnitOptions"
                :key="itm.id"
                :label="itm.label"
                :value="itm.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="市场价"
            prop="marketPrice"
          >
            <el-input
              v-model="productInfo.marketPrice"
              clearable
              placeholder="请输入市场价"
              @input="productInfo.marketPrice=productInfo.marketPrice.replace(/^\.+|[^\d.]/g,'')"
            >
              <template #append>
                <div><span>元</span><span v-if="productInfo.sellUnit"> / {{ getLabel('sell_unit',productInfo.sellUnit)||productInfo.sellUnitLabel }}</span></div>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="医保价"
            prop="medicalInsurancePrice"
          >
            <div class="marketPrice-form-item">
              <el-input
                v-model="productInfo.medicalInsurancePrice"
                clearable
                placeholder="请输入医保价"
                @input="productInfo.medicalInsurancePrice=productInfo.medicalInsurancePrice.replace(/^\.+|[^\d.]/g,'')"
              >
                <template #append>
                  <div><span>元</span><span v-if="productInfo.sellUnit"> / {{ getLabel('sell_unit',productInfo.sellUnit)||productInfo.sellUnitLabel }}</span></div>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="中包装"
            class="package-form-item"
            prop="mPack"
          >
            <div
              class="pack"
              style="width: 100%;display: flex;"
            >
              <el-input
                v-model="productInfo.mPackNum"
                style="width: 50%;"
                placeholder="包装数量"
                class="input-with-select"
                @input="productInfo.mPackNum=productInfo.mPackNum.replace(/[^\d]/g,'')"
                @blur="()=>productInfo.mPackNum = Number(productInfo.mPackNum)"
              />
              <span style="margin:0px 10px;">/</span>
              <el-select
                v-model="productInfo.mPackUnit"
                clearable
                filterable
                allow-create
                :reserve-keyword="false"
                placeholder="中包装单位"
                style="width:200px;"
                @visible-change="(val)=>{sellUnitChange(val,'mPackUnit')}"
              >
                <el-option
                  v-for="(itm) in sellUnitOptions"
                  :key="itm.id"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="大包装"
            class="package-form-item"
            prop="lPack"
          >
            <div
              class="pack"
              style="width: 100%;display: flex;"
            >
              <el-input
                v-model="productInfo.lPackNum"
                style="width: 50%;"
                placeholder="包装数量"
                class="input-with-select"
                @input="productInfo.lPackNum=productInfo.lPackNum.replace(/[^\d]/g,'')"
                @blur="()=>productInfo.lPackNum = Number(productInfo.lPackNum)"
              />
              <span style="margin:0px 10px;">/</span>
              <el-select
                v-model="productInfo.lPackUnit"
                clearable
                filterable
                allow-create
                :reserve-keyword="false"
                placeholder="大包装单位"
                style="width:200px;"
                @visible-change="(val)=>{sellUnitChange(val,'lPackUnit')}"
              >
                <el-option
                  v-for="(itm) in sellUnitOptions"
                  :key="itm.id"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="产品线"
            prop="productLine"
          >
            <el-select
              v-model="productInfo.productLine"
              style="width: 100%"
              clearable
              placeholder="请选择产品线"
            >
              <el-option
                v-for="(itm, idx) in productLineOptions"
                :key="itm.id"
                :label="itm.productLineName"
                :value="itm.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="产品属性"
            prop="productAttribute"
          >
            <el-select
              v-model="productInfo.productAttribute"
              style="width: 100%"
              clearable
              placeholder="请选择产品属性"
            >
              <el-option
                v-for="(itm, idx) in productAttributeOptions"
                :key="itm.id"
                :label="itm.label"
                :value="itm.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item
            label="其他描述"
            prop="remark"
          >
            <el-input
              v-model="productInfo.remark"
              type="textarea"
              placeholder="请输入其他描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item
            label="说明书"
            prop="instruction"
          >
            <image-upload v-model:fileList="productInfo.instruction" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item
            label="产品照片"
            prop="images"
          >
            <image-upload v-model:fileList="productInfo.images" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirmOperation"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { crmStore } from '@CRM/store'

export default defineComponent({
  name: 'CreateOrEidt',
  emits: ['success'],
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    var formRef = ref(null)
    var titleContent = ref('新建产品')
    var drug = ref(null)
    var productForm = reactive({
      dialogType: 'create',
      drugOptions: [],
      sellUnitOptions: [],
      productLineOptions: [],
      productAttributeOptions:
        crmStore.getters['dictionary/getDictionary']['product_attribute'],
      productInfo: {
        productNumber: '',
        productPopularName: '',
        productAlias: '',
        productName: '',
        approvalNumber: '',
        producer: '',
        packSpecs: '',
        drugForm: '',
        sellUnit: '',
        marketPrice: '',
        medicalInsurancePrice: null,
        mPackNum: null,
        mPackUnit: '',
        lPackNum: null,
        lPackUnit: '',
        productLine: '',
        productAttribute: '',
        remark: '',
        instruction: [],
        images: [],
      },
    })
    const aliasPass = async(rule, value, callback) => {
      if (value) {
        var res = await api.product.PRODUCT_ALIAS_CHECK({ productAlias: value })
        if (res.code === 0) {
          if (res.data === 0) {
            console.log(555)
            callback()
          } else {
            callback(new Error('产品别名重复'))
          }
        } else {
          callback(new Error(res.msg))
        }
      } else {
        callback()
      }
    }
    const marketPricePass = (rule, value, callback) => {
      if (value) {
        if (value > 0) {
          productForm.productInfo.marketPrice = Number(value)
          callback()
        } else {
          callback(new Error('市场价必须大于0'))
        }
      } else {
        callback(new Error('请输入市场价'))
      }
    }
    const medicalInsurancePricePass = (rule, value, callback) => {
      if (value) {
        if (value > 0) {
          productForm.productInfo.medicalInsurancePrice = Number(value)
          callback()
        } else {
          callback(new Error('医保价必须大于0'))
        }
      } else {
        callback()
      }
    }
    const mPackPass = (rule, value, callback) => {
      if (productForm.productInfo.mPackNum) {
        if (productForm.productInfo.mPackUnit) {
          // 单位相同
          if (
            productForm.productInfo.lPackUnit ===
            productForm.productInfo.mPackUnit
          ) {
            if (
              productForm.productInfo.mPackNum <=
              productForm.productInfo.lPackNum
            ) {
              callback()
            } else {
              callback(new Error('中包装数量不能大于大包装数量'))
            }
          } else {
            callback()
          }
        } else {
          callback(new Error('请选择中包装单位'))
        }
      } else {
        if (productForm.productInfo.mPackUnit) {
          callback(new Error('请输入中包装数量'))
        } else {
          callback()
        }
      }
    }
    const lPackPass = (rule, value, callback) => {
      if (productForm.productInfo.lPackNum) {
        if (productForm.productInfo.lPackUnit) {
          // 单位相同
          if (
            productForm.productInfo.lPackUnit ===
            productForm.productInfo.mPackUnit
          ) {
            if (
              productForm.productInfo.lPackNum >=
              productForm.productInfo.mPackNum
            ) {
              callback()
            } else {
              callback(new Error('大包装数量不能小于中包装数量'))
            }
          } else {
            callback()
          }
        } else {
          callback(new Error('请选择大包装单位'))
        }
      } else {
        if (productForm.productInfo.lPackUnit) {
          callback(new Error('请输入大包装数量'))
        } else {
          callback()
        }
      }
    }
    var rules = reactive({
      productNumber: [
        { required: false, message: '请输入产品编号', trigger: 'blur' },
      ],
      productName: [
        { required: false, message: '请输入产品名称', trigger: 'blur' },
      ],
      productPopularName: [
        { required: true, message: '请输入通用名', trigger: 'blur' },
      ],
      productAlias: [
        {
          required: false,
          validator: aliasPass,
          trigger: 'blur',
        },
      ],
      approvalNumber: [
        { required: true, message: '请输入批准文号', trigger: 'blur' },
      ],
      producer: [
        { required: true, message: '请输入生产厂家', trigger: 'blur' },
      ],
      packSpecs: [
        { required: true, message: '请输入包装规格', trigger: 'blur' },
      ],
      sellUnit: [
        { required: true, message: '请选择或输入计价单位', trigger: 'change' },
      ],
      mPack: [
        { required: false, validator: mPackPass, trigger: ['blur', 'change'] },
      ],
      lPack: [
        { required: false, validator: lPackPass, trigger: ['blur', 'change'] },
      ],
      mPackUnit: [
        { required: true, message: '请选择中包装单位', trigger: 'change' },
      ],
      marketPrice: [
        { required: true, validator: marketPricePass, trigger: 'blur' },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      medicalInsurancePrice: [
        {
          required: false,
          validator: medicalInsurancePricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      productLine: [
        { required: true, message: '请选择产品线', trigger: 'change' },
      ],
      productAttribute: [
        { required: true, message: '请选择产品属性', trigger: 'change' },
      ],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = (types, productId) => {
      productForm.dialogType = types
      if (productForm.dialogType === 'create') {
        titleContent.value = '新建产品'
      } else if (productForm.dialogType === 'change') {
        titleContent.value = '变更产品'
        getProductDetail(productId)
      } else if (productForm.dialogType === 'edit') {
        titleContent.value = '编辑产品'
        getProductDetail(productId)
      }
      // 产品线
      getProductLine()
      // 获取下拉数据
      productForm.drugOptions =
        crmStore.getters['dictionary/getDictionary']['drug_form'] || []
      productForm.sellUnitOptions =
        crmStore.getters['dictionary/getDictionary']['sell_unit'] || []
      console.log(productForm.dialogType)
      dialogShow.value = true
    }
    const close = () => {
      // 重置
      productForm.productInfo.mPackNum = null
      productForm.productInfo.lPackNum = null
      productForm.productInfo.mPackUnit = ''
      productForm.productInfo.lPackUnit = ''
      formRef.value.resetFields()
      dialogShow.value = false
    }
    // 剂型改变
    const drugChange = async(val) => {
      console.log(val, productForm.drugOptions)
      var exit = productForm.drugOptions.find(
        (p) => p.value === productForm.productInfo.drugForm
      )
      if (!val) {
        if (!exit && productForm.productInfo.drugForm) {
          var data = {
            types: 'drug_form',
            label: productForm.productInfo.drugForm,
            value: 'drug_' + new Date().getTime(),
          }
          // 创建字典
          var dictCreate = await api.common.DICTIONARY_CREATE(data)
          if (dictCreate.code === 0) {
            // 更新字典
            var dict = await crmStore.dispatch('dictionary/getDictionary')
            productForm.drugOptions = dict['drug_form'] || []
            productForm.productInfo.drugForm = data.value
          }
        }
      }
    }
    // 剂型改变
    const sellUnitChange = async(val, field) => {
      var exit = productForm.sellUnitOptions.find(
        (p) => p.value === productForm.productInfo[field]
      )
      if (!val) {
        if (!exit && productForm.productInfo[field]) {
          var data = {
            types: 'sell_unit',
            label: productForm.productInfo[field],
            value: 'sell_unit_' + new Date().getTime(),
          }
          // 创建字典
          var dictCreate = await api.common.DICTIONARY_CREATE(data)
          if (dictCreate.code === 0) {
            // 更新字典
            var dict = await crmStore.dispatch('dictionary/getDictionary')
            productForm.sellUnitOptions = dict['sell_unit'] || []
            productForm.productInfo[field] = data.value
            productForm.productInfo[field + 'Label'] = data.label
            console.log(
              productForm.productInfo[field],
              productForm.productInfo[field + 'Label']
            )
          }
        }
      }
    }

    const confirmOperation = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          console.log(666, productForm.productInfo)
          if (productForm.dialogType === 'create') {
            productCreate()
          } else if (productForm.dialogType === 'edit') {
            productEdit()
          } else if (productForm.dialogType === 'change') {
            productChange()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const getProductLine = () => {
      api.system.PRODUCTLINE_LIST().then((res) => {
        if (res.code === 0) {
          productForm.productLineOptions = res.data.list
        }
      })
    }
    const productCreate = () => {
      api.product.PRODUCT_CREATE(productForm.productInfo).then((res) => {
        if (res.code === 0) {
          context.emit('success')
          currentInstance.proxy.customMessage({
            type: 'success',
            message:
              '提交成功，已创建新建产品审批，可在[流程审批-我发起的]查看审批进程。',
          })
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const productEdit = () => {
      api.product.PRODUCT_EDIT(productForm.productInfo).then((res) => {
        if (res.code === 0) {
          context.emit('success')
          currentInstance.proxy.customMessage({
            type: 'success',
            message: '修改成功',
          })
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const productChange = () => {
      api.product.PRODUCT_CHANGE(productForm.productInfo).then((res) => {
        if (res.code === 0) {
          context.emit('success')
          currentInstance.proxy.customMessage({
            type: 'success',
            message:
              '提交成功，已创建变更产品审批，可在[流程审批-我发起的]查看审批进程。',
          })
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    // 获取产品详情
    const getProductDetail = (productId) => {
      api.product.PRODUCT_DETAIL({ id: productId }).then((res) => {
        if (res.code !== 0) {
          console.log(res.msg)
        } else {
          var detail = res.data.productInfo
          if (!detail.images) {
            detail.images = []
          }
          if (!detail.instruction) {
            detail.instruction = []
          }
          detail.mPackNum = detail.mPackNum !== 0 ? detail.mPackNum : null
          detail.lPackNum = detail.lPackNum !== 0 ? detail.lPackNum : null
          detail.medicalInsurancePrice =
            detail.medicalInsurancePrice !== 0
              ? detail.medicalInsurancePrice
              : null
          productForm.productInfo = detail
        }
      })
    }

    return {
      formRef,
      drug,
      titleContent,
      ...toRefs(productForm),
      rules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirmOperation,
      drugChange,
      sellUnitChange,
    }
  },
})
</script>

<style lang="scss">
.package-form-item {
  .el-input-group__append {
    background: transparent;
  }
}
</style>
